package com.taotao.cn.controller.authcode;

import com.alibaba.fastjson.JSON;
import com.octo.captcha.service.image.ImageCaptchaService;
import com.taotao.cn.bean.json.UserLoginJson;
import com.taotao.cn.bean.person.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 *
 * @author dimdark
 * @date 2017-03-13
 * @time 7:40 PM
 */
@Controller
@RequestMapping(value = "/normal")
public class JcaptchaImageCreater {

    //日志处理


    @Autowired
    private ImageCaptchaService imageCaptchaService;

    @RequestMapping("/captcha")
    public void handle(HttpServletRequest request, HttpServletResponse response){
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        String id = request.getSession().getId();
        BufferedImage chllenge = imageCaptchaService.getImageChallengeForID(id,request.getLocale());
//        System.out.println(chllenge==null);
        response.setHeader("Cache-Control","no-store");
        response.setHeader("Pragma","no-cache");
        response.setDateHeader("Expires",0L);
        response.setContentType("image/jpeg");
        try {
            ImageIO.write(chllenge,"jpeg",out);
            byte[] bs = out.toByteArray();
            ServletOutputStream servletOutputStream = response.getOutputStream();
            servletOutputStream.write(bs);
            servletOutputStream.flush();
            servletOutputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
            //日志处理
        }
    }

    @PostMapping(value = "/homepage", produces = "application/json")
    public @ResponseBody String toHomePage(@RequestBody UserLoginJson userLoginJson, HttpSession session){
       System.out.println(userLoginJson.toString());
        Map<String,Object> map = new HashMap<String,Object>();
        map.put("message","loginSuccess");
        Boolean codeCorrect = imageCaptchaService.validateResponseForID(session.getId(),userLoginJson.getAuthCode());
        if(!codeCorrect){
            map.put("message","codeError");
        }
        User user = new User();
        user.setUsername("aaa");
        user.setPassword("123");
        if(!user.getUsername().equals(userLoginJson.getUsername())||!user.getPassword().equals(userLoginJson.getPassword())){
            map.put("message","userError");
        }
        System.out.println(JSON.toJSONString(map));
        return JSON.toJSONString(map);
    }

}
